package com.yw.atp.action;

import java.text.MessageFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.yw.atp.model.Command;
import com.yw.atp.model.Consult;
import com.yw.atp.model.Department;
import com.yw.atp.model.Profession;
import com.yw.atp.model.Reply;
import com.yw.atp.model.Staff;
import com.yw.atp.model.Weather;
import com.yw.atp.service.CommandService;
import com.yw.atp.service.ConsultService;
import com.yw.atp.service.PersistenceService;
import com.yw.atp.service.ReplyService;
import com.yw.atp.service.StaffService;
import com.yw.atp.service.WeatherService;
import com.yw.atp.util.BeanUtil;
import com.yw.atp.util.Constants;
import com.yw.atp.util.PushUtil;
import com.yw.atp.util.StringUtil;
import com.yw.atp.web.ActionBase;

@Scope("prototype")
@Component("pollingAction")
public class PollingAction extends ActionBase implements ServletRequestAware{
	private static final long serialVersionUID = 1L;
	@Autowired
	private PersistenceService service;
	@Autowired
	private CommandService commandService;
	@Autowired
	private ConsultService consultService;
	@Autowired
	private ReplyService replyService;
	@Autowired
	private WeatherService weatherService;
	@Autowired
	private StaffService staffService;
	HttpServletRequest request;
	public String res = "{}";
	public String tType;//comm1:重要信息 comm2我来找茬 consult:观众反馈 wea:天气预报 replay:回复 turn:签表 match:每日对阵
	public String maxID;
	public String ids;
	public String mobileID;
	public String params;
	public String model = "-2";
	public String needRefrush = "0";
	public String version = "-1";
	public String list(){
		try {
			JSONObject js = new JSONObject();
			if("pro".equals(tType)){
				List<Profession> pList = service.findAll(Profession.class,0);
				js.put("topics",Profession.captureForSel(pList));
			}else if("depart".equals(tType)){
				List<Department> dList = service.findAll(Department.class,0);
				js.put("topics",Department.captureForSel(dList));
			}else if("staff".equals(tType)){
				List<Staff> sList = service.findAll(Staff.class,0);
				js.put("topics",Staff.captureForSel(sList));
			}
			res = js.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String polling(){
		Staff staff = staffService.findByMobile(mobileID);
		if(staff!=null&&staff.getId()!=null&&staff.getId().intValue()>0){
			int mid = -1;
			try{mid = Integer.valueOf(maxID).intValue();}catch(Exception e){mid=-1;}
		    ids = (ids==null||"".equals(ids))?"-1":ids;
			if(mid!=-1&&mobileID!=null&&!"".equals(mobileID)){
				if("comm1".equals(tType)||"comm2".equals(tType)){
					if("0".equals(version)){
						System.out.println("-----------------新版本notice------------------------");
						try{
							List<Command> commands = commandService.getPollingCommands(mid,ids,mobileID,"");
							if(commands!=null&&commands.size()>0){
								JSONObject jo = new JSONObject();
								JSONArray ja = new JSONArray();
								for(Command c:commands){
									if(c.getSender()!=null&&c.getSender().getId()!=null&&staff.getId().intValue() != c.getSender().getId().intValue()){
										try {
											Reply r = replyService.getTheReplysOfStaff(c,staff);
											ja.put(BeanUtil.formatCommand(c,r));
										} catch (Exception e){
										}
									}
								}
								jo.put("failure","false");
								jo.put("success","true");
								jo.put("maxID",commands.get(0).getId());
								jo.put("res",ja);
								res = jo.toString();
								return "commands";
							}else{
								return INPUT;
							}
						}catch(Exception e){return INPUT;}
					}else{
						pollingCommand(staff,"1",mid);
					}
				}else if("wea".equals(tType)){
					pollingWeather(staff,mid);
				}else if("replay".equals(tType)){
					pollingReply(staff,mid);
				}else if("consult".equals(tType)){
					pollingConsult(staff,mid);
				}else if("sqlStr".equals(tType)){
					System.out.println("------- sql " + params);
					if(StringUtil.isNotNull(params)){
						List<Object> list = service.excNativeQuery(params);
						System.out.println("------- list size : " + (list!=null?list.size():"null"));
						for(Object o:list){
							try{
								String r = String.valueOf(o);
								if(r!=null&&!"".equals(r)){
									pollingOther(staff,r,model);
								}
							}catch(Exception e){
								System.out.println("Push 异常 : " + e.getMessage());
							}
						}
					}
				}else{
					try{
						String[] param = StringUtil.parStr(params);
						String sql = Constants.get(tType,null);
						if(StringUtil.isNotNull(sql)){
							MessageFormat form = new MessageFormat(sql);
							String s = form.format(param);
							List<Object> list = service.excNativeQuery(s);
							for(Object o:list){
								try{
									String r = String.valueOf(o);
									pollingOther(staff,r,model);
								}catch(Exception e){
									System.out.println("Push 异常 : " + e.getMessage());
								}
							}
						}
					}catch(Exception e){
						return INPUT;
					}
				}
				try {
					if("1".equals(needRefrush)){
						PushUtil.polling(staff.getMobileID(),"0_0",maxID,false);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return SUCCESS;			
			}
		}
		return INPUT;
		
	}
	
	public void pollingOther(Staff staff,String val,String model) throws Exception{
		System.out.println("开始给 "+staff.getName()+ " Push  "+tType);
			PushUtil.polling(staff.getMobileID(),model+"_1",val,false);
	}
	
	public void pollingCommand(Staff staff,String commType,Integer mid){
			List<Command> commands = commandService.getPollingCommands(mid,ids,mobileID,commType);
			System.out.println("commands 有 "+ (commands!=null?commands.size():"0") + "消息需要 Push");
			if(commands!=null&&commands.size()>0){
				boolean isOk = true;
				for (Command command:commands){
					if(command.getSender()!=null&&command.getSender().getId()!=null&&staff.getId().intValue() != command.getSender().getId().intValue()){
						try {
							boolean isGet = false;
							System.out.println("开始给 "+staff.getName()+ " Push "+("1".equals(command.getCommType())?"重要信息":("2".equals(command.getCommType())?"我来找茬":"工作汇报")));
							Reply r = replyService.getTheReplysOfStaff(command,staff);
							PushUtil.polling(staff.getMobileID(),command.getCommType()+"_"+(isGet?"0":"1"),BeanUtil.formatCommand(command,r),isGet);
						} catch (Exception e){
							isOk = false;
							System.out.println("Push 异常 : " + e.getMessage());
						}
					}
				}
				if(isOk){
					maxID = String.valueOf(commands.get(0).getId());
				}
				try {
					PushUtil.polling(staff.getMobileID(),"8_0",maxID,false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	}
	
	public void pollingReply(Staff staff,Integer mid){
		List<Reply> replys = replyService.getPollingReplys(mid,ids,staff);
		System.out.println("replys 有 "+ (replys!=null?replys.size():"0") + "消息需要 Push");
		if(replys!=null&&replys.size()>0){
			boolean isOk = true;
			for(Reply reply:replys){
				try {
					boolean isGet = false;
					System.out.println("开始给 "+staff.getName()+ " Push "+"回复");
					PushUtil.polling(staff.getMobileID(),"3_"+(isGet?"0":"1"),BeanUtil.formatReply(reply),isGet);
				} catch (Exception e){
					isOk = false;
					System.out.println("Push 异常 : " + e.getMessage());
				}
			}
			if(isOk){
				maxID = String.valueOf(replys.get(0).getId());
			}
			try {
				//PushUtil.polling(staff.getMobileID(),"8_0",maxID,false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void pollingConsult(Staff staff,Integer mid){
		List<Consult> consults = consultService.getPollingConsults(mid,ids,staff);
		System.out.println("consults 有 "+ (consults!=null?consults.size():"0") + "消息需要 Push");
		if(consults!=null&&consults.size()>0){
			boolean isOk = true;
			for(Consult consult : consults){
				try {
					boolean isGet = false;
					System.out.println("开始给 "+staff.getName()+ " Push "+"观众反馈");
					PushUtil.polling(staff.getMobileID(),"5_"+(isGet?"0":"1"),BeanUtil.formatConsult(consult),isGet);
				} catch (Exception e){
					isOk = false;
					System.out.println("Push 异常 : " + e.getMessage());
				}
			}
			if(isOk){
				maxID = String.valueOf(consults.get(0).getId());
			}
			try {
				//PushUtil.polling(staff.getMobileID(),"8_0",maxID,false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void pollingWeather(Staff staff,Integer mid){
		//System.out.println("-------------sfdfdfdfd-----------------");
		List<Weather> weathers = weatherService.getPollingWeather(mid,ids,staff);
		System.out.println("weathers 有 "+ (weathers!=null?weathers.size():"0") + "消息需要 Push");
		if(weathers!=null&&weathers.size()>0){
			boolean isOk = true;
			for(Weather weather : weathers){
				try {
					boolean isGet = false;
					System.out.println("开始给 "+staff.getName()+ " Push "+"天气预报");
					PushUtil.polling(staff.getMobileID(),"4_"+(isGet?"0":"1"),BeanUtil.formatWeather(weather),isGet);
				} catch (Exception e){
					isOk = false;
					System.out.println("Push 异常 : " + e.getMessage());
				}
			}
			if(isOk){
				maxID = String.valueOf(weathers.get(0).getId());
			}
			try {
				//PushUtil.polling(staff.getMobileID(),"8_0",maxID,false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public String loadSerInfo(){
		try{
			Staff staff = staffService.findByMobile(mobileID);
			if(staff!=null&&staff.getId()!=null&&staff.getId().intValue()>0){
				try{
					if(StringUtil.isNotNull(params)){
						if(params.indexOf("FROM atp_match")!=-1){
							params = Constants.getSql("match");
						}
						//System.out.println("--------------------load sql:"+params);
						List<Object> list = service.excNativeQuery(params);
						if(list!=null&&list.size()>0){
							JSONObject jo = new JSONObject();
							JSONArray ja = new JSONArray();
							for(Object o:list){
								ja.put((String)o);
							}
							jo.put("failure","false");
							jo.put("success","true");
							jo.put("res",ja);
							res = jo.toString();
							return SUCCESS;
						}
					}
				}catch(Exception e){
					return INPUT;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return INPUT;
	}
	
	public String execSql(){
		try{
			Staff staff = staffService.findByMobile(mobileID);
			System.out.println((staff!=null?staff.getName():" nobody ")+" need exec sql ");
			if(staff!=null&&staff.getId()!=null&&staff.getId().intValue()>0){
				try{
					//System.out.println("----------------  exec  sql  id : " + params);
					if(StringUtil.isNotNull(params)){
						String sql = Constants.getSql(params);
						//System.out.println("----------------  exec  sql  : " + sql);
						if(StringUtil.isNotNull(sql)){
							List<Object> list = service.excNativeQuery(sql);
							if(list!=null&&list.size()>0){
								JSONObject jo = new JSONObject();
								JSONArray ja = new JSONArray();
								for(Object o:list){
									ja.put((String)o);
								}
								jo.put("failure","false");
								jo.put("success","true");
								jo.put("res",ja);
								res = jo.toString();
								//System.out.println("-------------exec sql res : ----------------"+res);
								return SUCCESS;
							}
						}
					}
				}catch(Exception e){
					return INPUT;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return INPUT;
	}
	
	public String getParams() {
		return params;
	}

	public void setParams(String params) {
		this.params = params;
	}
	
	public void setServletRequest(HttpServletRequest request) {
        if(request==null){
            request = ServletActionContext.getRequest();
        }
        this.request = request;
    }
	
	public PersistenceService getService() {
		return service;
	}
	
	public void setService(PersistenceService service) {
		this.service = service;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}
	
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public String getRes() {
		return res;
	}

	public void setRes(String res) {
		this.res = res;
	}
	public String gettType() {
		return tType;
	}

	public void settType(String tType) {
		this.tType = tType;
	}
	
	public String getMaxID() {
		return maxID;
	}

	public void setMaxID(String maxID) {
		this.maxID = maxID;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public CommandService getCommandService() {
		return commandService;
	}

	public void setCommandService(CommandService commandService) {
		this.commandService = commandService;
	}

	public ConsultService getConsultService() {
		return consultService;
	}

	public void setConsultService(ConsultService consultService) {
		this.consultService = consultService;
	}

	public ReplyService getReplyService() {
		return replyService;
	}

	public void setReplyService(ReplyService replyService) {
		this.replyService = replyService;
	}

	public WeatherService getWeatherService() {
		return weatherService;
	}

	public void setWeatherService(WeatherService weatherService) {
		this.weatherService = weatherService;
	}

	public String getMobileID() {
		return mobileID;
	}

	public void setMobileID(String mobileID) {
		this.mobileID = mobileID;
	}
	
	public StaffService getStaffService() {
		return staffService;
	}

	public void setStaffService(StaffService staffService) {
		this.staffService = staffService;
	}
	
	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public String getNeedRefrush() {
		return needRefrush;
	}

	public void setNeedRefrush(String needRefrush) {
		this.needRefrush = needRefrush;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}
}
